package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DIshServiceImpl1 implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品和对应的口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional //涉及到多表操作，需要保持一致性
    public void insertDish(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insertDish(dish);

        /**
         * useGeneratedKeys="true"：告诉 MyBatis：我要用数据库自动生成的主键。
         * keyProperty="id"：指定这个主键应该填回哪个 Java 对象的属性。
         */
        //获取insert语句生成的主键值,执行完 insert 语句后，ORM 框架自动把数据库生成的主键填充进了你传入的 dish 对象中。
        Long id = dish.getId();
        //添加菜品的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断用户是否添加口味
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            //口味不止一种
            dishFlavorMapper.insertDishFlavor(flavors);
        }

    }

    @Override
    public PageResult pageSelect(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageSelect(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //1.判断该菜品是否能够删除，启用状态的菜品不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品是售卖状态，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2.菜品是否关联套餐，关联套餐的菜品不能删除
        List<Long> setmealIds = setMealDishMapper.getSetmealByDishIds(ids);
        if (setmealIds != null && setmealIds.size() >0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3.删除菜品表中的菜品、删除菜品相关联的风味
        /*for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品口味
            dishFlavorMapper.deleteByDishIds(id);
        }*/

        //改进代码
        dishMapper.deleteById(ids);
        dishFlavorMapper.deleteByDishIds(ids);



    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                                 .status(status)
                                         .id(id)
                                                 .build();
        dishMapper.updateStatus(dish);
    }

    @Override
    public void updateDishMessage(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateStatus(dish);

        //先删除之前的所有口味，然后在添加新的口味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        Long id = dishDTO.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //可能有多种口味
        if (flavors != null && flavors.size() >0){
            flavors.forEach(DishFlavor ->{
                DishFlavor.setDishId(id);
            });
            dishFlavorMapper.insertDishFlavor(flavors);
        }

    }

    @Override
    public DishVO getById(Long id) {
        //根据id查询到菜品信息
        Dish dish = dishMapper.getById(id);
        //属性拷贝
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        List<DishFlavor> byDishId = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(byDishId);
       // BeanUtils.copyProperties(byDishId,dishVO);
        return dishVO;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //查询传进来的categoryid下的所有起售的菜品  select * from dish where categort_id = #{categoryId} and status = #{status}
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        //遍历每个菜品，得到每个菜品的口味
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
